package com.sunwayworld.basemodule.coredata.test.resource.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.sunwayworld.basemodule.coredata.test.resource.LimsTestResource;
import com.sunwayworld.basemodule.coredata.test.service.LimsTestService;
import com.sunwayworld.basemodule.coredata.test.validators.LimsTestDeleteTableValidator;
import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.log.annotation.Log;
import com.sunwayworld.framework.log.annotation.LogModule;
import com.sunwayworld.framework.log.annotation.LogType;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.restful.data.RestValidationResultBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.validator.data.annotation.ValidateDataWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@LogModule("工序")
@RestController
@GikamBean
public class LimsTestResourceImpl implements LimsTestResource {

    @Autowired
    private LimsTestService limsTestService;

    @Override
    public LimsTestService getService() {
        return limsTestService;
    }

    @Log(value = "新增工序", type = LogType.INSERT)
    @Override
    @RequestMapping(method = RequestMethod.POST)
    public Long insert(RestJsonWrapperBean wrapper) {
        return getService().insert(wrapper);
    }

    @Log(value = "删除", type = LogType.DELETE)
    @ValidateDataWith(LimsTestDeleteTableValidator.class)
    @Override
    public void delete(RestJsonWrapperBean wrapper) {
        getService().delete(wrapper);
    }

    @Override
    public RestValidationResultBean validateFormul(RestJsonWrapperBean wrapper) {
        String validateJson = wrapper.getParamValue("vu");
        if (null == validateJson) return new RestValidationResultBean(true);
        Map<String, String> validateMap = JSONObject.parseObject(validateJson,new TypeReference<Map<String,String>>(){});
        String formula = validateMap.get("formula");
        if(formula != null && valid(formula))  {
            return new RestValidationResultBean(false, I18nHelper.getMessage("CORE_TEST.FORMUL_VALIDATE_MESSAGE"));
        }
        return new RestValidationResultBean(true);
    }

    // 校验公式中是否包含特定字符
    private static boolean valid(String obj){
        Pattern pattern= Pattern.compile("import|exec");
        Matcher matcher=pattern.matcher(obj.toLowerCase());
        return matcher.find();
    }

    @Override
    public String testItemScript(RestJsonWrapperBean wrapper) {
        return getService().testItemScript(wrapper);
    }
}
